package com.lnsf.bookstore.system.admin.controller;

import com.lnsf.bookstore.common.annotation.SysLog;
import com.lnsf.bookstore.common.constant.Constants;
import com.google.code.kaptcha.Producer;
import com.lnsf.bookstore.common.dto.ResultFailDto;
import com.lnsf.bookstore.common.dto.ResultSuccessDto;
import com.lnsf.bookstore.common.session.SessionProvider;
import com.lnsf.bookstore.system.model.vo.UserVo;
import com.lnsf.bookstore.system.permission.service.PermissionService;
import com.lnsf.bookstore.system.permission.vo.Permission;
import com.lnsf.bookstore.system.role.service.RoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lnsf.bookstore.system.user.service.UserService;
import com.lnsf.bookstore.system.user.vo.User;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

@Controller
public class AdminLoginController {

	@Autowired
	private UserService userService;

	@Autowired
	private Producer producer;

	@Autowired
	private RoleService roleService;

	@Autowired
	private PermissionService permissionService;

	@Autowired
	private SessionProvider sessionProvider;

	@RequestMapping("/tologin")
	public String toLogin(){
	System.out.println("aaa");
		return "admin/login/login";
	}

	@RequestMapping("/captcha.jpg")
	public void captcha(HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		//生成文字验证码
		String text = producer.createText();
		//生成图片验证码
		BufferedImage image = producer.createImage(text);
		//保存到shiro session
		sessionProvider.setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, text);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
	}


	@SysLog("管理员登录")
	@RequestMapping("/login")
	@ResponseBody
	public Object login(UserVo user , String captcha ,  Model model){
		String msg = null;
		Subject subject = SecurityUtils.getSubject();
		String kaptcha = sessionProvider.getKaptcha(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (!captcha.equalsIgnoreCase(kaptcha)) {
			return new ResultFailDto("验证码不正确");
		}
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
		//UPToken token = new UPToken(vipuser.getPhone(), vipuser.getPassword());
		try {
			subject.login(token);
			//将用户信息存入session
			//sessionProvider.setUser(vipuser);
			msg="登录成功.The account for username"+ token.getPrincipal() ;
		} catch (IncorrectCredentialsException e) {
	        msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";  
	        model.addAttribute("message", msg);  
	        System.out.println(msg);
			return  new ResultFailDto("登录密码错误.");
	    } catch (ExcessiveAttemptsException e) {
	        msg = "登录失败次数过多";  
	        model.addAttribute("message", msg);  
	        System.out.println(msg);
			return  new ResultFailDto("登录失败次数过多.");
	    } catch (LockedAccountException e) {
	        msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";  
	        model.addAttribute("message", msg);
	        System.out.println(msg);
			return  new ResultFailDto("帐号已被锁定.");
	    } catch (DisabledAccountException e) {
	        msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";  
	        model.addAttribute("message", msg);  
	        System.out.println(msg);
			return  new ResultFailDto("帐号已被禁用.");
	    } catch (ExpiredCredentialsException e) {  
	        msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";  
	        model.addAttribute("message", msg);  
	        System.out.println(msg);
			return  new ResultFailDto("帐号已过期.");
	    } catch (UnknownAccountException e) {  
	        msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
	        model.addAttribute("message", msg);  
	        System.out.println(msg);
			return  new ResultFailDto("帐号不存在.");
	    } catch (UnauthorizedException e) {
	        msg = "您没有得到相应的授权！" + e.getMessage();  
	        model.addAttribute("message", msg);  
	        System.out.println(msg);
			return  new ResultFailDto("您没有得到相应的授权！");
	    }
		ResultSuccessDto  resultSuccessDto= new ResultSuccessDto(msg);
		return  resultSuccessDto;

	}

	@RequestMapping(value = "/index.html")
	public String home(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		return "admin/index/index";
	}

	@RequestMapping("/main_default")
	public String main(Model model) {
		return "admin/index/main";
	}
	
	@RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(Model model){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        model.addAttribute("msg","您已经退出登录");
        return "admin/login/login";
    }
	 


}
